package com.example.lets;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bmob.BmobPro;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.DownloadListener;
import com.bmob.btp.callback.LocalThumbnailListener;
import com.gc.materialdesign.views.AutoHideButtonFloat;
import com.github.ksoichiro.android.observablescrollview.ObservableListView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.widget.CircleImageView;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.listener.FindListener;

public class HomeActivity extends BaseActivity implements ObservableScrollViewCallbacks {

    private static int DATESORT = 1;
    private static int LOCSORT = 0;

    private Toolbar mToolbarView;
    private boolean hasQuery = false;
    private DrawerLayout mDrawerLayout;
    private ArrayList<HashMap<String, Object>> listItem = new ArrayList<>();
    private MyAdapter adapter;
    public static BmobGeoPoint curLoc;
    private int page = 0;
    private int sortType = LOCSORT;
    public PullToRefreshActLayout pullLayout;

    public static ObservableListView homeList;
    public static boolean hasNew = false;
    public static boolean isTop = true;
    public static boolean isBottom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        final User user = BmobUser.getCurrentUser(this, User.class);
        Integer num = user.getFrequency();
        if (num == null) num = 1;
        else num++;
        user.setFrequency(num);
        user.update(this);
        ///
        /// toolbar
        ///
        mToolbarView = (Toolbar) this.findViewById(R.id.home_toolbar);
        setSupportActionBar(mToolbarView);
        if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        setTitle(BmobUser.getCurrentUser(this, User.class).getNickname());

        mToolbarView.setNavigationIcon(R.drawable.list_icon_white);
        mToolbarView.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                Intent intent = new Intent(HomeActivity.this, SearchActivity.class);
                startActivity(intent);
                HomeActivity.this.finish();
                return false;
            }
        });

        ///
        /// drawer layout
        ///
        mDrawerLayout = (DrawerLayout) this.findViewById(R.id.dl_left);

        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbarView,
                R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };
        mDrawerToggle.syncState();
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        LinearLayout joined = (LinearLayout) this.findViewById(R.id.drawer_joined);
        LinearLayout initiated = (LinearLayout) this.findViewById(R.id.drawer_initiated);
        LinearLayout center = (LinearLayout) this.findViewById(R.id.drawer_center);
        LinearLayout logout = (LinearLayout) this.findViewById(R.id.drawer_logout);
        LinearLayout feedback = (LinearLayout) this.findViewById(R.id.drawer_feedback);
        View head = this.findViewById(R.id.drawer_head);
        center.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, MeActivity.class);
                startActivity(intent);
            }
        });
        joined.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BmobUser currentUser = BmobUser.getCurrentUser(HomeActivity.this);
                final String id = currentUser.getObjectId();
                Intent intent = new Intent(HomeActivity.this, UserActivityList.class);
                intent.putExtra("title", "我加入的活动");
                intent.putExtra("mode", "joined");
                intent.putExtra("input", id);
                startActivity(intent);
            }
        });
        initiated.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BmobUser currentUser = BmobUser.getCurrentUser(HomeActivity.this);
                final String id = currentUser.getObjectId();
                Intent intent = new Intent(HomeActivity.this, UserActivityList.class);
                intent.putExtra("title", "我发起的活动");
                intent.putExtra("mode", "sponsored");
                intent.putExtra("input", id);
                startActivity(intent);
            }
        });
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BmobUser.logOut(HomeActivity.this);
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, MainActivity.class);
                startActivity(intent);
                HomeActivity.this.finish();
            }
        });
        feedback.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HomeActivity.this, FeedbackActivity.class);
                startActivity(intent);
            }
        });
        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("username", user.getNickname());
                intent.putExtra("userid", user.getObjectId());
                intent.putExtra("userpicname", user.getPicFilename());
                intent.putExtra("userdescription", user.getDescription());
                intent.setClass(HomeActivity.this, UserPageActivity.class);
                startActivity(intent);
            }
        });


        ///
        /// drawer information
        ///
        final Context context = HomeActivity.this;
        final CircleImageView userImage = (CircleImageView) findViewById(R.id.drawer_head);
        final TextView nickname = (TextView) this.findViewById(R.id.drawer_nickname);
        final TextView otherinfo = (TextView) this.findViewById(R.id.drawer_other_info);

        User curUser = BmobUser.getCurrentUser(context, User.class);

        nickname.setText(curUser.getNickname());
        otherinfo.setText(curUser.getTag1() + ", " + curUser.getTag2() + ", " + curUser.getTag3());

        String cacheDownloadPath = BmobPro.getInstance(context).getCacheDownloadDir() + "/" + curUser.getPicFilename();
        String[] name = curUser.getPicFilename().split("\\.");
        String newFileName = name[0] + "_1_200_0_100." + name[1];
        String cacheThumbnailPath = BmobPro.getInstance(context).getCacheThumbnailDir() + "/" + newFileName;

        if ((new File(cacheDownloadPath)).exists()) { // 判断是否存在文件

            if ((new File(cacheThumbnailPath)).exists()) { // 判断是否存在缓存

                Bitmap bm = BitmapFactory.decodeFile(cacheThumbnailPath);
                userImage.setImageBitmap(bm);

            } else { // 缓存不存在则重新生成缓存

                BmobProFile.getInstance(context).getLocalThumbnail(cacheDownloadPath, 1, new LocalThumbnailListener() {

                    @Override
                    public void onSuccess(String thumbnailPath) {
                        Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                        userImage.setImageBitmap(bm);
                    }

                    @Override
                    public void onError(int statuscode, String errormsg) {
                    }
                });
            }
        } else { // 文件不存在需要重新下载
            BmobProFile.getInstance(context).download(curUser.getPicFilename(), new DownloadListener() {

                @Override
                public void onSuccess(String fullPath) {
                    Log.i("bmob", "????????" + fullPath);
                    BmobProFile.getInstance(context).getLocalThumbnail(fullPath, 1, new LocalThumbnailListener() {

                        @Override
                        public void onSuccess(String thumbnailPath) {
                            Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                            userImage.setImageBitmap(bm);
                        }

                        @Override
                        public void onError(int statuscode, String errormsg) {
                        }
                    });
                    String str = BmobPro.getInstance(context).getCacheDownloadDir();
                    Log.i("bmob", str);
                }

                @Override
                public void onProgress(String localPath, int percent) {
                }

                @Override
                public void onError(int statuscode, String errormsg) {

                }
            });
        }

        ///
        /// main frame
        ///
        homeList = (ObservableListView) this.findViewById(R.id.home_list);
        LayoutInflater inflater = LayoutInflater.from(HomeActivity.this);
        View tableButtons = inflater.inflate(R.layout.types_group_table_layout, null);
        homeList.addHeaderView(tableButtons, null, false);
        homeList.setScrollViewCallbacks(this);


        ///
        /// float button
        ///
        AutoHideButtonFloat initiateButton = (AutoHideButtonFloat)
                this.findViewById(R.id.home_initiate_event_button);
        initiateButton.setRippleSpeed(10.0f);
        // set icon
        ImageView imageView = new ImageView(HomeActivity.this);
        Drawable drawable = getResources().getDrawable(R.drawable.initiate_event_button);
        imageView.setImageDrawable(drawable);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        imageView.setLayoutParams(params);
        initiateButton.addView(imageView);
        initiateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HomeActivity.this, InitiateEventActivity.class);
                intent.putExtra("mode", "init");
                intent.putExtra("title", "发起活动");
                startActivity(intent);
                HomeActivity.this.finish();
            }
        });

        ///
        /// type image buttons
        ///
        ImageView sportButton = (ImageView) this.findViewById(R.id.SportButton);
        sportButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String type = "sport";
                Intent intent = new Intent(HomeActivity.this, UserActivityList.class);
                intent.putExtra("title", "运动");
                intent.putExtra("mode", "type");
                intent.putExtra("input", type);
                startActivity(intent);
            }
        });

        ImageView foodButton = (ImageView) this.findViewById(R.id.FoodButton);
        foodButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String type = "food";
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, UserActivityList.class);
                intent.putExtra("title", "美食");
                intent.putExtra("mode", "type");
                intent.putExtra("input", type);
                startActivity(intent);
            }
        });

        ImageView tourButton = (ImageView) this.findViewById(R.id.TravelButton);
        tourButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String type = "tour";
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, UserActivityList.class);
                intent.putExtra("title", "旅游");
                intent.putExtra("mode", "type");
                intent.putExtra("input", type);
                startActivity(intent);
            }
        });

        ImageView studyButton = (ImageView) this.findViewById(R.id.StudyButton);
        studyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String type = "study";
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, UserActivityList.class);
                intent.putExtra("title", "学习");
                intent.putExtra("mode", "type");
                intent.putExtra("input", type);
                startActivity(intent);
            }
        });

        ImageView gameButton = (ImageView) this.findViewById(R.id.GameButton);
        gameButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String type = "game";
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, UserActivityList.class);
                intent.putExtra("title", "游戏");
                intent.putExtra("mode", "type");
                intent.putExtra("input", type);
                startActivity(intent);
            }
        });

        ImageView movieButton = (ImageView) this.findViewById(R.id.MovieButton);
        movieButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String type = "movie";
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, UserActivityList.class);
                intent.putExtra("title", "影视");
                intent.putExtra("mode", "type");
                intent.putExtra("input", type);
                startActivity(intent);
            }
        });

        if (!hasQuery) {
            listItem = new ArrayList<>();
            adapter = new MyAdapter(this, listItem);
            homeList.setAdapter(adapter);
            hasQuery = true;
        }

        Spinner spinner = (Spinner) findViewById(R.id.sort_type_spinner);
        spinner.setSelection(0);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                sortType = i;
                pullLayout.autoRefresh();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.home, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
        Log.i("ui", "scrollY = " + scrollY);
        isTop = scrollY == 0;
    }

    public boolean ifReachBottom() {
        if (homeList.getLastVisiblePosition() == homeList.getCount() - 1) {
            int lastIndex = homeList.getLastVisiblePosition() - homeList.getFirstVisiblePosition();
            View lastItem = homeList.getChildAt(lastIndex);
            int height = lastItem.getMeasuredHeight();
            int location[] = new int[2];
            lastItem.getLocationInWindow(location);
            int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
            isBottom = location[1] <= screenHeight - height;
        } else isBottom = false;
        return isBottom;
    }

    @Override
    public void onDownMotionEvent() {

    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {

    }

    private class MyLocationListenner implements BDLocationListener {

        private int type;
        private RefreshActListener listener;

        public MyLocationListenner(final RefreshActListener listener, int type) {
            this.listener = listener;
            this.type = type;
        }

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                Toast.makeText(HomeActivity.this, "定位服务未开启！", Toast.LENGTH_SHORT).show();
                if (listener != null) {
                    if (type == 1)
                        listener.refreshFinish(PullToRefreshActLayout.FAIL);
                    else
                        listener.loadFinish(PullToRefreshActLayout.FAIL, 0);
                }
                return;
            }
            int res = location.getLocType();
            if (res != 61 && res != 65 && res != 66 && res != 68 && res != 161) {
                switch (res) {
                    case 62:
                        Toast.makeText(HomeActivity.this, "扫描整合定位依据失败，定位结果无效", Toast.LENGTH_SHORT).show();
                        break;
                    case 63:
                        Toast.makeText(HomeActivity.this, "网络异常，定位失败", Toast.LENGTH_SHORT).show();
                        break;
                    case 67:
                        Toast.makeText(HomeActivity.this, "离线定位失败", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        Toast.makeText(HomeActivity.this, "服务端异常，定位失败", Toast.LENGTH_SHORT).show();
                }
                if (listener != null) {
                    if (type == 1)
                        listener.refreshFinish(PullToRefreshActLayout.FAIL);
                    else
                        listener.loadFinish(PullToRefreshActLayout.FAIL, 0);
                }
                return;
            }
            BmobQuery<UserActivity> bmobQuery = new BmobQuery<>();
            curLoc = new BmobGeoPoint(location.getLongitude(), location.getLatitude());
            bmobQuery.addWhereNear("gpsAdd", curLoc);
            bmobQuery.addWhereWithinKilometers("gpsAdd", curLoc, 500);
            bmobQuery.setLimit(15);
            if (type != 1) bmobQuery.setSkip(page * 15);

            bmobQuery.findObjects(HomeActivity.this, new FindListener<UserActivity>() {

                @Override
                public void onSuccess(List<UserActivity> object) {
                    page++;
                    if (type == 1) listItem = new ArrayList<HashMap<String, Object>>();
                    setList(object, listener);
                    if (listener == null || type == 1) {
                        adapter = new MyAdapter(HomeActivity.this, listItem);
                        homeList.setAdapter(adapter);
                        if (type == 1) listener.refreshFinish(PullToRefreshActLayout.SUCCEED);
                    } else {
                        hasNew = object.size() != 0;
                        adapter.notifyDataSetChanged();
                        listener.loadFinish(hasNew ? PullToRefreshActLayout.SUCCEED : PullToRefreshActLayout.NOMORE, object.size());
                    }
                }

                @Override
                public void onError(int code, String msg) {
                    Toast.makeText(HomeActivity.this, "下载失败，网络异常！" + msg, Toast.LENGTH_SHORT).show();
                    if (listener != null) {
                        if (type == 1)
                            listener.refreshFinish(PullToRefreshActLayout.FAIL);
                        else
                            listener.loadFinish(PullToRefreshActLayout.FAIL, 0);
                    }
                }
            });

        }
    }

    public void loadActivities(final RefreshActListener listener, final int type) {

        BmobQuery<UserActivity> query = new BmobQuery<UserActivity>();

        if (sortType == LOCSORT) {
            // 若为按地点排序，UI的更新将在定位监听器中实现，else部分将跳过
            LocationClient mLocClient;
            mLocClient = new LocationClient(this);
            mLocClient.registerLocationListener(new MyLocationListenner(listener, type));
            LocationClientOption option = new LocationClientOption();
            option.setOpenGps(true); // 打开gps
            option.setCoorType("bd09ll"); // 设置坐标类型
            option.setScanSpan(0);
            mLocClient.setLocOption(option);
            mLocClient.start();
        } else {
            // 若为按时间排序，UI的更新将在此时直接完成
            Date currentTime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = sdf.format(currentTime);
            Date date = null;
            try {
                date = sdf.parse(dateString);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            query.addWhereGreaterThanOrEqualTo("startTime", new BmobDate(date));
            query.order("startTime");

            query.setLimit(15);
            if (type != 1) query.setSkip(page * 15);

            // 由于采用了分页加载的方式，导致之前写的一次性排序失效，
            // 正确的做法应该是在服务端将一个list排好序后多页传给手机端

            query.findObjects(this, new FindListener<UserActivity>() {

                @Override
                public void onSuccess(List<UserActivity> object) {
                    page++;
                    if (type == 1) listItem = new ArrayList<HashMap<String, Object>>();
                    setList(object, listener);
                    if (listener == null || type == 1) {
                        adapter = new MyAdapter(HomeActivity.this, listItem);
                        homeList.setAdapter(adapter);
                        if (type == 1) listener.refreshFinish(PullToRefreshActLayout.SUCCEED);
                    } else {
                        hasNew = object.size() != 0;
                        adapter.notifyDataSetChanged();
                        listener.loadFinish(hasNew ? PullToRefreshActLayout.SUCCEED : PullToRefreshActLayout.NOMORE, object.size());
                    }
                }

                @Override
                public void onError(int code, String msg) {
                    Toast.makeText(HomeActivity.this, "下载失败，网络异常！", Toast.LENGTH_SHORT).show();
                    if (listener != null) {
                        if (type == 1)
                            listener.refreshFinish(PullToRefreshActLayout.FAIL);
                        else
                            listener.loadFinish(PullToRefreshActLayout.FAIL, 0);
                    }
                }
            });
        }
    }

    private void setList(List<UserActivity> object, RefreshActListener listener) {
        for (UserActivity activity : object) {
            HashMap<String, Object> map = new HashMap<String, Object>();

            int dateLength = activity.getStartTime().getDate().length();
            Double dis = curLoc.distanceInKilometersTo(activity.getGpsAdd());
            BigDecimal b = new BigDecimal(dis);
            Double _dis = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            map.put("distance", _dis.toString());
            map.put("ItemSponsor", activity.getSponsorName());
            map.put("ItemPicFileName", activity.getPicFilename());
            map.put("ItemTitle", activity.getName());
            map.put("ItemText", activity.getDescription());
            map.put("number", activity.getPeopleNumber());
            map.put("sponsorId", activity.getSponsorId());
            map.put("place", activity.getPlace());
            map.put("detail", activity.getDetailPlace());
            map.put("time", activity.getStartTime().getDate().substring(0, dateLength - 3));
            map.put("type", activity.getType());
            map.put("id", activity.getObjectId());
            listItem.add(map);
        }

        if (listener == null) {
            adapter = new MyAdapter(HomeActivity.this, listItem);
            homeList.setAdapter(adapter);
            homeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {

                    if (position < 1) return;
                    position -= 1;

                    String title = (String) listItem.get(position).get("ItemTitle");
                    String description = (String) listItem.get(position).get("ItemText");
                    String picFileName = (String) listItem.get(position).get("ItemPicFileName");
                    String sponsorId = (String) listItem.get(position).get("sponsorId");
                    String type = (String) listItem.get(position).get("type");
                    String place = (String) listItem.get(position).get("place");
                    String detail = (String) listItem.get(position).get("detail");
                    String time = (String) listItem.get(position).get("time");
                    String actiId = (String) listItem.get(position).get("id");
                    String dis = (String) listItem.get(position).get("distance");

                    Intent intent = new Intent(HomeActivity.this, EventActivity.class);
                    intent.putExtra("title", title);
                    intent.putExtra("description", description);
                    intent.putExtra("picFileName", picFileName);
                    intent.putExtra("sponsorId", sponsorId);
                    intent.putExtra("place", place);
                    intent.putExtra("detail", detail);
                    intent.putExtra("time", time);
                    intent.putExtra("type", type);
                    intent.putExtra("id", actiId);
                    intent.putExtra("distance", dis);

                    startActivity(intent);
                }

            });
        }
    }

    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        startActivity(intent);
        return;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    private boolean isFirst = true;
    @Override
    public void onResume() {
        super.onResume();
        if (!isFirst) return;
        isFirst = false;
        final int type = 0;
        BmobQuery<UserActivity> query = new BmobQuery<UserActivity>();

        if (sortType == LOCSORT) {
            // 若为按地点排序，UI的更新将在定位监听器中实现，else部分将跳过
            LocationClient mLocClient;
            mLocClient = new LocationClient(this);
            mLocClient.registerLocationListener(new MyLocationListenner(null, type));
            LocationClientOption option = new LocationClientOption();
            option.setOpenGps(true);// 打开gps
            option.setCoorType("bd09ll"); // 设置坐标类型
            option.setScanSpan(0);
            mLocClient.setLocOption(option);
            mLocClient.start();
        } else {
            // 若为按时间排序，UI的更新将在此时直接完成
            Date currentTime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = sdf.format(currentTime);
            Date date = null;
            try {
                date = sdf.parse(dateString);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            query.addWhereGreaterThanOrEqualTo("startTime", new BmobDate(date));
            query.order("startTime");

            query.setLimit(15);
            if (type != 1) query.setSkip(page * 15);

            // 由于采用了分页加载的方式，导致之前写的一次性排序失效，
            // 正确的做法应该是在服务端将一个list排好序后多页传给手机端

            query.findObjects(this, new FindListener<UserActivity>() {

                @Override
                public void onSuccess(List<UserActivity> object) {
                    page++;
                    if (type == 1) listItem = new ArrayList<HashMap<String, Object>>();
                    setList(object, null);
                    adapter = new MyAdapter(HomeActivity.this, listItem);
                    homeList.setAdapter(adapter);
                }

                @Override
                public void onError(int code, String msg) {
                    Toast.makeText(HomeActivity.this, "下载失败，网络异常！", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    class LoadActivityTask extends AsyncTask<Void,Integer,Integer> {

        private Context context;
        private RefreshActListener listener;

        public LoadActivityTask(Context context, RefreshActListener listener) {
            this.context = context;
            this.listener = listener;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {


            return null;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {

        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }
}

